﻿using System;
using FreeRedis;
using LeoGemini.Service.Infrastructure.Extension;
using Microsoft.Extensions.Configuration;
using UserService.Application.Constract.IAppService;
using Volo.Abp.DependencyInjection;

namespace UserService.Application.AppService
{
    /// <summary>
    /// 验证码管理类
    /// </summary>
    public class VerifyCodeManager : IVerifyCodeManager, ITransientDependency
    {
        private readonly RedisClient _cache;
        private readonly IConfiguration _configuration;
        
        public VerifyCodeManager(
            RedisClient cache,
            IConfiguration configuration)
        {
            _cache = cache;
            _configuration = configuration;
        }
        
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="verifyAction">枚举自VerifyAction</param>
        public string GenerateVerifyCode(Guid userId, string verifyAction)
        {
            // 获取验证码
            var verifyCode = new Random().Next(6, Extensions.MixinType.JustNum);
            
            // 缓存验证码
            _cache.Set($"user:{userId}:{verifyAction}", 
                verifyCode, 
                // 过期时间 30分钟
                _configuration.GetValue<int>("Cache:ExpireTime:VerifyCode"));

            return verifyCode;
        }

        /// <summary>
        /// 获取已生成的用户验证码
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="verifyAction">枚举自VerifyAction</param>
        public string GetGeneratedVerifyCode(Guid userId, string verifyAction)
        {
            return _cache.Get<string>($"user:{userId}:{verifyAction}");
        }

        /// <summary>
        /// 销毁已生成的用户验证码
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="verifyAction">枚举自VerifyAction</param>
        public void DestroyGeneratedVerifyCode(Guid userId, string verifyAction)
        {
            _cache.Del($"user:{userId}:{verifyAction}");
        }
    }
}